package com.baitiaojun.elasticsearch.service.impl;

import com.baitiaojun.api.vo.PageInfo;
import com.baitiaojun.elasticsearch.service.FullTextSearchService;
import io.netty.util.internal.StringUtil;
import org.apache.commons.lang3.ObjectUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.text.Text;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.index.query.MultiMatchQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortBuilders;
import org.elasticsearch.search.sort.SortOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.net.ConnectException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @类名 FullTextSearchServiceImpl
 * @描述 TODO
 * @作者 白条君
 * @创建日期 2023/1/5 12:48
 * @版本 1.0
 */
@Service
public class FullTextSearchServiceImpl implements FullTextSearchService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public PageInfo searchContent(String keyword, Integer pageNo, Integer pageSize) throws IOException {
        if (StringUtil.isNullOrEmpty(keyword)) {
            throw new ConnectException("检索关键词不能为空");
        }
        SearchRequest request = new SearchRequest();
        SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
        String[] fields = {"title", "nick"};
        //指定索引
        String[] indices = {"video", "user_info"};
        request.indices(indices);
        //添加条件为关键字次检索
        MultiMatchQueryBuilder queryBuilder = QueryBuilders.multiMatchQuery(keyword, fields);
        searchSourceBuilder.query(queryBuilder);
        //字段过滤
        String[] excludes = {"type", "area", "gender", "creatime", "updatetime", "birth", "url", "userid"};
        searchSourceBuilder.fetchSource(null, excludes);
        //分页和排序
        searchSourceBuilder.from(pageNo - 1);
        searchSourceBuilder.size(pageSize);
        searchSourceBuilder.sort(SortBuilders.fieldSort("createtime").order(SortOrder.DESC));
        //指定超时时间
        searchSourceBuilder.timeout(new TimeValue(60, TimeUnit.SECONDS));
        //添加规则
        request.source(searchSourceBuilder);
        //高亮，分词显示
        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.requireFieldMatch(false); //多个字段需要设置高亮，requireFieldMatch必须设置为false
        highlightBuilder.preTags("<span style=\"color:rgb(244,94,137)\">");
        highlightBuilder.postTags("</span>");
        List<HighlightBuilder.Field> fieldsList = highlightBuilder.fields();
        for (String field : fields) {
            fieldsList.add(new HighlightBuilder.Field(field));
        }
        searchSourceBuilder.highlighter(highlightBuilder);
        //搜索
        SearchResponse searchResponse = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        SearchHits hits = searchResponse.getHits();
        List<Map<String, Object>> list = new ArrayList<>();
        Map<String, HighlightField> highlightFields;
        HighlightField highlightField;
        Text[] fragments;
        String fragmentStr;
        String substring;
        for (SearchHit hit : hits) {
            Map<String, Object> sourceAsMap = hit.getSourceAsMap();
            //高亮处理
            highlightFields = hit.getHighlightFields();
            for (String field : fields) {
                highlightField = highlightFields.get(field);
                if (ObjectUtils.isNotEmpty(highlightField)) {
                    fragments = highlightField.fragments();
                    fragmentStr = Arrays.toString(fragments);
                    substring = fragmentStr.substring(1, fragmentStr.length() - 1);
                    sourceAsMap.put(field, substring);
                }
            }
            list.add(sourceAsMap);
        }
        return PageInfo.builder().pageList(list).size(list.size()).build();
    }
}